<?php

namespace App\Kuafu\CouponPackage\Command;

use App\Kuafu\CouponPackage\Model\CouponPackageModel;
use App\Kuafu\CouponPackage\Model\CouponPackageOrderModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CloseNonPayOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'coupon-package:close-non-pay-order {start?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '优惠券包 - 自动关闭超时未支付订单';

    /**
     * Create a new command instance.
     *
     * @return void//
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command
     *
     * @return int
     */
    public function handle()
    {
        // 订单超时秒数
        $timeout = 900;

        $end = time() - $timeout;

        // 开始时间
        $start = $this->argument('start') ?? $end - 1200;

        CouponPackageOrderModel::query()
                               ->whereBetween('createdAt', [$start, $end])
                               ->where('payStatus', CouponPackageOrderModel::PAY_STATUS_0)
                               ->select('couponPackageId', 'orderId')
                               ->get()
                               ->each(function ($item) {
                                   $cId     = $item->couponPackageId;
                                   $orderId = $item->orderId;

                                   DB::beginTransaction();
                                   CouponPackageOrderModel::payFail($orderId);
                                   CouponPackageModel::reIncrStock($cId);
                                   DB::commit();

                                   dump("orderId:{$orderId} close...");
                                   Log::info("CloseNonPayOrder orderId: {$orderId}");
                               });
    }
}
